/*
 * GuudDraw.cpp
 *
 *  Created on: 2013-1-27
 *      Author: heqiu
 */

#include "GuudDraw.h"
namespace guud {
void GuudDraw::drawPoint(SDL_Surface *screen, int x, int y, GuudColor & gc) {
	Uint32 color = SDL_MapRGB(screen->format, gc.m_color.r, gc.m_color.g,
			gc.m_color.b);
	switch (screen->format->BytesPerPixel) {
	case 1: // Assuming 8-bpp
	{
		Uint8 *bufp;
		bufp = (Uint8 *) screen->pixels + y * screen->pitch + x;
		*bufp = color;
	}
		break;
	case 2: // Probably 15-bpp or 16-bpp
	{
		Uint16 *bufp;
		bufp = (Uint16 *) screen->pixels + y * screen->pitch / 2 + x;
		*bufp = color;
	}
		break;
	case 3: // Slow 24-bpp mode, usually not used
	{
		Uint8 *bufp;
		bufp = (Uint8 *) screen->pixels + y * screen->pitch + x * 3;
		if (SDL_BYTEORDER == SDL_LIL_ENDIAN) {
			bufp[0] = color;
			bufp[1] = color >> 8;
			bufp[2] = color >> 16;
		} else {
			bufp[2] = color;
			bufp[1] = color >> 8;
			bufp[0] = color >> 16;
		}
	}
		break;
	case 4: // Probably 32-bpp
	{
		Uint32 *bufp;
		bufp = (Uint32 *) screen->pixels + y * screen->pitch / 4 + x;
		*bufp = color;
	}
		break;
	}
}

void GuudDraw::drawLine(SDL_Surface *surface, int xa, int ya, int xb, int yb,
		GuudColor & c, uint32_t uiWidth, uint32_t uiHeight) {
	float delta_x, delta_y, x, y;
	int dx, dy, steps, k;
	dx = xb - xa;
	dy = yb - ya;

	if (abs(dx) > abs(dy))
		steps = abs(dx);
	else
		steps = abs(dy);
	if (steps == 0) {
		return;
	}
	delta_x = (float) dx / (float) steps;
	delta_y = (float) dy / (float) steps;
	x = xa;
	y = ya;
	if (x >= 0 && y >= 0 && x < uiWidth && y < uiHeight) {
		drawPoint(surface, x, y, c);
	}
	for (k = 0; k < steps; k++) {
		x += delta_x;
		y += delta_y;
		if (x >= 0 && y >= 0 && x < uiWidth && y < uiHeight) {
			drawPoint(surface, x, y, c);
		}
	}
	return;
}

}
